//
//  KtvhttpCacheTestViewController.m
//  TestPrj
//
//  Created by 朱铅峰 on 2020/1/8.
//  Copyright © 2020 Xing. All rights reserved.
//

#import "KtvhttpCacheTestViewController.h"
#import <ZFPlayer/ZFPlayer.h>
#import <ZFPlayer/ZFAVPlayerManager.h>
#import <ZFPlayer/ZFPlayerController.h>
#import <ZFPlayer/ZFPlayerControlView.h>
#import <Masonry.h>
#import <SDWebImage.h>
#import <KTVHTTPCache.h>
#import <Toast.h>

static NSString *kVideoCover = @"https://upload-images.jianshu.io/upload_images/635942-14593722fe3f0695.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240";

/*
 KTVHTTPCache在客户端搭建local服务器，local服务器作为中间者，代替客户端请求服务器数据，并将获取到的数据缓存，再提供给客户端。
 参考文章：
 https://www.jianshu.com/p/2314782a16c3
 https://www.jianshu.com/p/7daec9ce6390
 */
@interface KtvhttpCacheTestViewController ()

@property(nonatomic, strong) ZFPlayerController *player;

@property(nonatomic, strong) UIImageView *containerView;
@property(nonatomic, strong) ZFPlayerControlView *controlView;
@property(nonatomic, strong) UIButton *playBtn;

@property(nonatomic,copy) NSString *URLString;

@end

@implementation KtvhttpCacheTestViewController

- (void)loadView {
    
    [super loadView];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:self.containerView];
    [self.containerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(20);
        make.right.mas_equalTo(-20);
        make.top.equalTo(self.mas_topLayoutGuide).offset(20);
        make.height.equalTo(self.containerView.mas_width).multipliedBy(9/16.0);
    }];
    
    [self.containerView addSubview:self.playBtn];
    [self.playBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(44);
        make.centerX.mas_equalTo(self.containerView.mas_centerX);
        make.centerY.mas_equalTo(self.containerView.mas_centerY);
    }];
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    NSError *error = nil;
    BOOL ifStart = [KTVHTTPCache proxyStart:&error];
    if (ifStart && !error) {
        NSLog(@"___开启KTVHTTPCache");
        [KTVHTTPCache downloadSetTimeoutInterval:10];
        [KTVHTTPCache logSetConsoleLogEnable:YES];
    }
    
    self.URLString = @"http://flv3.bn.netease.com/tvmrepo/2018/6/9/R/EDJTRAD9R/SD/EDJTRAD9R-mobile.mp4";
}

- (void)dealloc {
    
    [KTVHTTPCache proxyStop];
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    self.player.viewControllerDisappear = NO;
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    self.player.viewControllerDisappear = YES;
}

/// 结束播放回调
- (void)didFinishPlayAction {
    
    NSURL *completeCacheFileURL= [KTVHTTPCache cacheCompleteFileURLWithURL:[NSURL URLWithString:self.URLString]];
    if ([[NSFileManager defaultManager] fileExistsAtPath:[completeCacheFileURL path]]) {
        [self.view makeToast:@"检测到本地的视频缓存文件"];
        NSLog(@"__视频文件：%@",[completeCacheFileURL path]);
    } else {
        [self.view makeToast:@"未检测到本地的视频缓存文件"];
    }
    
    [self.player stop];
}

#pragma mark - 事件处理

- (void)playClick:(UIButton *)sender {
    
    NSURL *proxyUrl = [KTVHTTPCache proxyURLWithOriginalURL:[NSURL URLWithString:self.URLString]];
    NSLog(@"===========================");
    NSLog(@"原始url：%@",self.URLString);
    NSLog(@"代理url：%@",[proxyUrl absoluteURL]);
    NSLog(@"===========================");
    
    NSURL *completeCacheFileURL= [KTVHTTPCache cacheCompleteFileURLWithURL:[NSURL URLWithString:self.URLString]];
    if ([[NSFileManager defaultManager] fileExistsAtPath:[completeCacheFileURL path]]) {
        [KTVHTTPCache cacheDeleteCacheWithURL:[NSURL URLWithString:self.URLString]];
        if (![[NSFileManager defaultManager] fileExistsAtPath:[completeCacheFileURL path]]) {
            [KTVHTTPCache cacheDeleteCacheWithURL:[NSURL URLWithString:self.URLString]];
            [self.view makeToast:@"已清除本地的视频缓存文件"];
        }
    } else {
        [self.view makeToast:@"本地不存在视频缓存文件"];
    }
    
    _player.assetURL = proxyUrl;
    
    [self.controlView showTitle:@"视频标题" coverURLString:kVideoCover fullScreenMode:ZFFullScreenModeAutomatic];
}


#pragma mark - 控制状态栏

- (UIStatusBarStyle)preferredStatusBarStyle {
    
    if (self.player.isFullScreen) {
        return UIStatusBarStyleLightContent;
    }
    return UIStatusBarStyleDefault;
}

- (BOOL)prefersStatusBarHidden {
    
    /// 如果只是支持iOS9+ 那直接return NO即可，这里为了适配iOS8
    return self.player.isStatusBarHidden;
}

- (UIStatusBarAnimation)preferredStatusBarUpdateAnimation {
    
    return UIStatusBarAnimationSlide;
}

- (BOOL)shouldAutorotate {
    
    return self.player.shouldAutorotate;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    
    if (self.player.isFullScreen) {
        return UIInterfaceOrientationMaskLandscape;
    }
    return UIInterfaceOrientationMaskPortrait;
}


#pragma mark - 懒加载

- (ZFPlayerController *)player {
    
    if (!_player) {
        
        @weakify(self)
        ZFAVPlayerManager *playerManager = [[ZFAVPlayerManager alloc] init];
        
        _player = [ZFPlayerController playerWithPlayerManager:playerManager containerView:self.containerView];
        _player.controlView = self.controlView;
        _player.pauseWhenAppResignActive = NO;//设置退到后台继续播放
        _player.orientationWillChange = ^(ZFPlayerController * _Nonnull player, BOOL isFullScreen) {
            @strongify(self)
            [self setNeedsStatusBarAppearanceUpdate];
        };
        _player.playerDidToEnd = ^(id<ZFPlayerMediaPlayback>  _Nonnull asset) {
            @strongify(self)
            [self didFinishPlayAction];
        };
    }
    
    return _player;
}

- (ZFPlayerControlView *)controlView {
    
    if (!_controlView) {
        _controlView = [ZFPlayerControlView new];
        _controlView.fastViewAnimated = YES;
        _controlView.autoHiddenTimeInterval = 5;
        _controlView.autoFadeTimeInterval = 0.5;
        _controlView.prepareShowLoading = YES;
        _controlView.prepareShowControlView = YES;
    }
    
    return _controlView;
}

- (UIImageView *)containerView {
    
    if (!_containerView) {
        
        _containerView = [[UIImageView alloc] init];
        [_containerView sd_setImageWithURL:[NSURL URLWithString:kVideoCover]];
        _containerView.backgroundColor = [UIColor blackColor];
    }
    
    return _containerView;
}

- (UIButton *)playBtn {
    if (!_playBtn) {
        _playBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_playBtn setImage:[UIImage imageNamed:@"new_allPlay_44x44_"] forState:UIControlStateNormal];
        [_playBtn addTarget:self action:@selector(playClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _playBtn;
}

@end

